package com.hzz.filter;


import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;

import javax.servlet.ReadListener;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.Part;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Collection;

/**
 *
 */
public class BodyReaderRequestWrapper extends HttpServletRequestWrapper {

    private final String body;

    private String bodyString;

    public BodyReaderRequestWrapper(HttpServletRequest request) throws IOException {
        super(request);

        StringBuilder sb = new StringBuilder();

        try (InputStream ins = request.getInputStream();
             BufferedReader isr = new BufferedReader(new InputStreamReader(ins))) {

            char[] charBuffer = new char[128];
            int readCount = 0;

            while ((readCount = isr.read(charBuffer)) != -1) {
                sb.append(charBuffer, 0, readCount);
            }

        } catch (IOException e) {
            throw e;
        }

        body = sb.toString();
    }

    public BodyReaderRequestWrapper(HttpServletRequest request, String body) throws IOException {
        super(request);
        this.body = body;
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(this.getInputStream()));
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        final ByteArrayInputStream byteArrayIns = new ByteArrayInputStream(body.getBytes());
        return new ServletInputStream() {
            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }

            @Override
            public int read() throws IOException {
                return byteArrayIns.read();
            }
        };
    }

    @Override
    public Collection<Part> getParts() throws IOException, ServletException {
        return super.getParts();
    }

    public String getBodyString() {
        try {
            if (StringUtils.isEmpty(bodyString)) {
                bodyString = StreamUtils.copyToString(this.getInputStream(), StandardCharsets.UTF_8);
            }
            return bodyString;
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }

}
